package com.ebelter.btcomlib.models.bluetooth.products.scale;


import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.text.TextUtils;


import com.ebelter.btcomlib.R;
import com.ebelter.btcomlib.bases.activity.BaseActivity;
import com.ebelter.btcomlib.models.beans.ScaleUser;
import com.ebelter.btcomlib.models.bluetooth.base.BaseManager;

import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.bean.SendMessage;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IDataReadWriteCallback;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IScaleUpdateCallback;
import com.ebelter.btcomlib.models.bluetooth.products.scale.interfaces.IScaleMeasureCallback;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.SpUtil;
import com.ebelter.btcomlib.utils.log.LogUtils;
import java.util.Arrays;
import java.util.List;


/**
 * 体脂秤
 */
public class ScaleManager extends BaseManager{

    private static final String TAG = "ScaleManager";




    private ScaleBytesMakeFatory mScaleBytesMakeFatory;//制包工具类

    private ScaleBytesAnalysisFatory mScaleBytesAnalysisFatory;//解包工具类

    private ScaleOtaUpdate mScaleOtaUpdate;//ota的升级工具类

    public ScaleManager(Context mContext,long ServiceGatt_SendThread_interval) {
        super(mContext, ProductStyle.SCALE,ScaleConstant.SCALE_SERVICE_UUID,
                new String[]{ScaleConstant.SCALE_WRITE_UUID},new String[]{ScaleConstant.SCALE_READ_UUID},
                true,ServiceGatt_SendThread_interval);


        mScaleBytesMakeFatory=new ScaleBytesMakeFatory();

        mScaleBytesAnalysisFatory=new ScaleBytesAnalysisFatory();

        mScaleOtaUpdate = new ScaleOtaUpdate(this,mScaleBytesMakeFatory);

        mScaleBytesAnalysisFatory.setScaleOtaUpdate(mScaleOtaUpdate);



        mServiceGatt.setIDataReadWriteCallback(new IDataReadWriteCallback() {
            @Override
            public void onCharacteristicChanged(byte[] data) {
              //  LogUtils.i(TAG,"ScaleBlue--IDataReadWriteCallback-onCharacteristicChanged--读到-"+ Arrays.toString(data));
                mScaleBytesAnalysisFatory.resultAnalysis(data);
            }

            @Override
            public void writeData(byte[] data) {
                // LogUtils.i(TAG,"ScaleBlue--IDataReadWriteCallback-writeData--写入-"+ Arrays.toString(data));
            }
        });
    }



    //设置升级更新回调器
    public void setmScaleOtaUpdateListener(IScaleUpdateCallback mScaleOtaUpdateListener){
        mScaleOtaUpdate.setmScaleOtaUpdateListener(mScaleOtaUpdateListener);
    }


    //开始Ota更新
    public void startOtaUpdate(){
        if (!isConnect()){
            LogUtils.i(TAG,"检测到设备未连接，无法进行Ota更新");
            return;
        }
        mScaleOtaUpdate.startOtaUpdate();
    }



    //设置测量状态监听
    public void setmIMeasureResultCallback(IScaleMeasureCallback mIMeasureResultCallback) {
        mScaleBytesAnalysisFatory.setmIMeasureResultCallback(mIMeasureResultCallback);
    }






    //下发用户信息 下发设置成功后会在在IMeasureResultCallback中setUserInfoSuccess()回调回来
    public void sendUserInfo(ScaleUser scaleUser){
        if (scaleUser==null)return;
        LogUtils.i2(TAG,"---下发用户信息 scaleUser="+scaleUser);
        addSendMsg(mScaleBytesMakeFatory.getUserInfoSmg(scaleUser));
    }


    //发送心跳包
    public void sendHeartCheck(){
        addSendMsg(mScaleBytesMakeFatory.getHEARTSmg());
    }


    public void getVersion(){
        addSendMsg(mScaleBytesMakeFatory.getVersion());
    }



    //通过btid来获取历史数据 结果在IMeasureResultCallback中onReceiveHistoryRecord(OfflineMeasureResult result)回调回来
    //数据请求完会回调IMeasureResultCallback中onHistoryDownloadDone()
    public void sendGetHistoryDataRequest(String uid){

        BluetoothDevice bluetoothDevice = getConnectBluetooth();
        String name=ScaleConstant.SCALE_NAME2;//默认为Body Fat-B2的秤

        if (bluetoothDevice!=null){
            name=bluetoothDevice.getName();
        }

        addSendMsg(mScaleBytesMakeFatory.getHistoryDataSmg(uid,name));
    }

    public void sendGetHistoryDataACK() {
        addSendMsg(mScaleBytesMakeFatory.getetHistoryDataACK());
    }

    public void sendMesureDataACK() {
        addSendMsg(mScaleBytesMakeFatory.getMesureDataACK());
    }


    public void sendMsg(SendMessage msg, String desc){
        LogUtils.i(TAG,"----sendMsg--"+desc);
        addSendMsg(msg);
    }

    public void sendMsgs(List<SendMessage> msgs, String desc) {
        LogUtils.i(TAG,"----sendMsgs--"+desc);
        addSendMsgs(msgs);
    }

    /**
     * 下发同步系统时间命令
     */
    public void syncSystemClock() {
        LogUtils.i(TAG, "----syncSystemClock-----send sync system time cmd.");
        addSendMsg(mScaleBytesMakeFatory.getSyncSystemClock());
    }

    public void deleteAllUserInfo() {
        addSendMsg(mScaleBytesMakeFatory.deleteAllUserInfo());
    }






    public void setSleepDisconnectTime(int time) {
        LogUtils.i(TAG,"体脂秤发送了设置休眠时间断开的指令");
        addSendMsg(mScaleBytesMakeFatory.getSleepDisconnectTime(time));
    }




    public boolean isBondDevice(){
        String add=getBondDeviceAddress();
        return !TextUtils.isEmpty(add);
    }

    public String getBondDeviceAddress(){
        return SpUtil.readString(ScaleConstant.SCALE_BOND_DEVICE_ADDRESS,null);
    }

    public void setBondDeviceAddress(String address){
        SpUtil.writeString(ScaleConstant.SCALE_BOND_DEVICE_ADDRESS,address);
    }


    //kg转磅
    public static float kg2lb(float kg){
        return (float) (kg * 144480.0/65536.0);
    }
    //磅转kg
    public static float lb2kg(float lb){
        return (float) (lb * 65536.0/144480.0);
    }

    //设置更新状态
    public void setUpdateFlag(boolean updateFlag) {
        if (mScaleOtaUpdate!=null)mScaleOtaUpdate.setUpdateing_Flag(updateFlag);
    }



    public static String getBMIDesc(float bmi){
        bmi= NumUtils.numBaoLiuWei1(bmi);
        if (bmi<18.5f){
            return BaseActivity.getString_(R.string.pianqing);
        }else if (bmi>=18.5f&&bmi<=23.9f){
            return BaseActivity.getString_(R.string.biaozhun);
        }else if (bmi>=24.0f&&bmi<=27.9f){
            return BaseActivity.getString_(R.string.pianzhong);
        }else {
            return BaseActivity.getString_(R.string.chaozhong);
        }
    }


    /**
     *
     * @param bmi
     * @return 0偏轻 1标准 2偏重 3超重
     */
    public static int getBMILevel(float bmi){
        bmi= NumUtils.numBaoLiuWei1(bmi);
        if (bmi<18.5f){
            return 0;
        }else if (bmi>=18.5f&&bmi<=23.9f){
            return 1;
        }else if (bmi>=24.0f&&bmi<=27.9f){
            return 2;
        }else {
            return 3;
        }
    }


}
